<template>
  <Card v-model="cardtype">
    <div class="md:flex md:mb-5">
      <div class="text-3xl font-semibold" style="color: #4e598c">应用续订/退订率（汇总）</div>
    </div>
    <div class="md:flex">
      <OperationAppStepTimePicker
        class="w-full enter-x"
        ref="OperationAppStepTimePickerRef"
        :initData="initOperationAppStepTimeRange"
        @success="handleSuccess"
      >
      </OperationAppStepTimePicker>
    </div>
    <div class="md:flex">
      <div :id="lineChartName" style="width: 800%; height: 450%"></div>
    </div>
  </Card>
</template>

<script setup lang="ts">
import { Card } from 'ant-design-vue';
import { onMounted, ref, defineProps } from 'vue';
import moment from 'moment';
import * as echarts from 'echarts';
import OperationAppStepTimePicker from '../../../components/OperationAppStepTimePicker.vue';
import { getAppSubRate } from '/@/api/operation-center/tenant-opertation/app-subscription-analysis/appSubscriptionAnalysis';
import { AppSubRateMap } from '/@/api/operation-center/tenant-opertation/app-subscription-analysis/model/appSubscriptionModel';

let props = defineProps({
  cardType: String,
});
const cardtype = ref(props.cardType);
var option;

const OperationAppStepTimePickerRef = ref();

let startDate = moment().add(-9, 'months').format('YYYY-MM-DD HH:mm:ss');

let stepTimeRange = {
  stepType: 0,
  startTime: startDate,
  endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
};

let lineChartName = 'app-renewal-unsub-rate-in-total-line-chart';

const initOperationAppStepTimeRange = ref();

function collectAppRenewalUnsubRateList(appRenewalUnsubRateDtoList: AppSubRateMap[], dateList: Array<any>, rateList: Array<any>) {
  for (let i = 0; i < appRenewalUnsubRateDtoList.length; i++) {
    let appRenewalUnsubRateItem = appRenewalUnsubRateDtoList[i];
    dateList.push(appRenewalUnsubRateItem.time);
    rateList.push(appRenewalUnsubRateItem.renewOrUnsubRate);
  }
}

const handleSuccess = (params) => {
  let lineChartDom = document.getElementById(lineChartName);

  let myChart = echarts.init(lineChartDom);

  let picTitle = params.statisticalIndicator === 0 ? '续订率' : '退订率';

  let dateList = [];
  let rateList = [];

  getAppSubRate(params).then((res) => {
    collectAppRenewalUnsubRateList(res, dateList, rateList);
    option = {
      title: {
        text: picTitle,
      },
      xAxis: {
        type: 'category',
        data: dateList,
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: rateList,
          type: 'line',
        },
      ],
    };

    option && myChart.setOption(option);
  });
};

onMounted(() => {
  initOperationAppStepTimeRange.value = {
    statisticalIndicator: 0,
    appId: '',
    stepType: 0,
    startTime: moment(stepTimeRange.startTime, 'YYYY-MM'),
    endTime: moment(stepTimeRange.endTime, 'YYYY-MM'),
  };
});
</script>
